<template>
  <div>
    <el-form
      :model="addForm"
      ref="addFormRef"
      :rules="rules"
      label-position="top"
    >
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="addForm.customerName"
          readonly
          @click="handleClickCustomer"
          placeholder="请选择客户"
        />
      </el-form-item>
      <el-form-item label="回访时间" prop="estimatedVisitTime">
        <el-date-picker
          v-model="addForm.estimatedVisitTime"
          type="date"
          placeholder="请选择回访时间"
          format="YYYY-MM-DD"
          value-format="x"
          class="w-full"
        />
      </el-form-item>
    </el-form>

    <div class="fixed bottom-2 right-2">
      <el-button @click="handleCancel(0)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ loading ? "提交中..." : "提交" }}
      </el-button>
    </div>

    <el-drawer
      v-model="customer_drawer"
      destory-on-close
      title="选择客户"
      size="80%"
    >
      <ChangeCustomer @handleBack="handleBack" />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import ChangeCustomer from "@/components/ChangeCustomer.vue";
import { handleApiResponse } from "@/utils/request.js";
import { CreateVisitRecord } from "../../../../../wailsjs/go/api/CustomerApi";

onMounted(() => {});

const emit = defineEmits(["handleBack"]);

const addFormRef = ref(null);
const addForm = ref({
  customerId: null,
  customerName: "",
  estimatedVisitTime: null,
});

const handleCancel = (val = 0) => {
  addFormRef.value.resetFields();
  emit("handleBack", val);
};

const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    loading.value = true;

    let form = cloneDeep(addForm.value);
    form.estimatedVisitTime = form.estimatedVisitTime / 1000;

    handleApiResponse(() => CreateVisitRecord(form)).then((res) => {
      if (res.code == 0) {
        ElMessage.success("新增成功");
        handleCancel(1);
      }
      loading.value = false;
    });
  });
};

// 1.点击选择客户
const customer_drawer = ref(false);
const handleClickCustomer = () => {
  customer_drawer.value = true;
};
const handleBack = (val) => {
  addForm.value.customerId = val.customerId;
  addForm.value.customerName = val.name;
  customer_drawer.value = false;
};

const rules = ref({
  customerName: [{ required: true, message: "请点击选择客户" }],
  estimatedVisitTime: [{ required: true, message: "请选择预计回访时间" }],
});
</script>

<style scoped lang="scss">
</style>